package threadDemo;

/**
 * 三个窗口同时售票问题，共100张票
 */
public class TicketWindown {
    public static void main(String[] args) {
        TicketThread ticketThread = new TicketThread();
        ticketThread.setName("窗口1");
        ticketThread.start();

        TicketThread ticketThread1 = new TicketThread();
        ticketThread1.setName("窗口2");
        ticketThread1.start();

        TicketThread ticketThread2 = new TicketThread();
        ticketThread2.setName("窗口3");
        ticketThread2.start();
    }
}

/**
 * static int ticket = 100;//声明为static
 * 好处：表示多个线程共用此变量
 * 不好处：生命周期太长，要等到TicketThread不用的时候，才会从内存中清除
 */
class TicketThread extends Thread {
    static int ticket = 100;//声明为static 表示多个线程公用100张票，否则的话都是各自100张票
    static Object obj = new Object();//必须加static，否则锁不是唯一的
    @Override
    public void run() {
        //super.run();
        while (true) {
            //同步机制：使用同步代码块加锁，保证线程安全
            synchronized (obj) {//这里慎用this
                if (ticket > 0) {
                    try {
                        Thread.currentThread().sleep(20);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "售票，票号为：" + ticket--);
                } else {
                    break;
                }
            }
        }
    }
}
